package priv.bestbeat.cloud.api.gateway.decoretors;

import io.netty.buffer.UnpooledByteBufAllocator;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import reactor.core.publisher.Flux;

/**
 * 可重用 ServerHttpRequest
 * @author bestbeat
 * @date 2021/12/19
 */
public class ReusableServerHttpRequest extends ServerHttpRequestDecorator {

    private byte[] bytes;

    public ReusableServerHttpRequest(ServerHttpRequest delegate) {
        super(delegate);
    }

    @Override
    public Flux<DataBuffer> getBody() {

        if (this.bytes == null || this.bytes.length == 0) {
            return this.getDelegate().getBody().map(dataBuffer -> {
                int byteCount = dataBuffer.readableByteCount();
                byte[] bytes = new byte[byteCount];
                dataBuffer.read(bytes);
                this.bytes = bytes;
                NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
                return nettyDataBufferFactory.wrap(this.bytes);
            });

        }
        NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(new UnpooledByteBufAllocator(false));
        return Flux.just(nettyDataBufferFactory.wrap(this.bytes));
    }
}
